package com.geeklan.smart.ui.pet;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.CaseInfo;
import com.geeklan.smart.data.remote.oss.AsyncMultiFileUploader;
import com.geeklan.smart.data.remote.oss.UploadMultifileCallback;
import com.geeklan.smart.data.repository.pet.PetRepository;
import com.geeklan.smart.databinding.ActivityCaseInfoBinding;
import com.geeklan.smart.permission.PermissionManager;
import com.geeklan.smart.ui.dialog.DelCaseAlertDialog;
import com.geeklan.smart.ui.dialog.DelDeviceAlertDialog;
import com.geeklan.smart.ui.pet.adapter.PhotoAdapter;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModel;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModelFactory;
import com.geeklan.smart.utils.DialogUtils;
import com.geeklan.smart.utils.GlideEngine;
import com.geeklan.smart.utils.ImagePathUtils;
import com.geeklan.smart.utils.ListUtils;
import com.geeklan.smart.widget.GridSpacingItemDecoration;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import gun0912.tedimagepicker.builder.TedImagePicker;

public class CaseInfoActivity extends BaseActivity<ActivityCaseInfoBinding> implements PhotoAdapter.PhotoAdapterListener {
    private PhotoAdapter photoAdapter;
    private List<String> photoList = new ArrayList<>();

    private ArrayList<String> uploadUrl = new ArrayList<>();
    private String petCaseName;
    private PetViewModel petViewModel;
    private CaseInfo caseInfo;
    private int petId;
    private boolean isEdit = false;

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    protected ActivityCaseInfoBinding initBinding() {
        return ActivityCaseInfoBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        petId = getIntent().getIntExtra("petId", 0);
        caseInfo = (CaseInfo) getIntent().getSerializableExtra("caseInfo");
        petViewModel = new ViewModelProvider(this, new PetViewModelFactory(new PetRepository())).get(PetViewModel.class);

        petViewModel.getAddCaseLiveData().observe(this, response -> {
            Toast.makeText(this, isEdit ? "修改成功" : "添加成功", Toast.LENGTH_SHORT).show();
            dismiss();
            finish();
        });

        petViewModel.getAddCaseErrorLiveData().observe(this, s -> {
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            dismiss();
        });


        petViewModel.getDelCaseLiveData().observe(this, response -> {
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
            dismiss();
            finish();
        });

        petViewModel.getDelCaseErrorLiveData().observe(this, s -> {
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            dismiss();
        });

        if (caseInfo != null) {
            isEdit = true;
            mBinding.ivRight.setVisibility(View.VISIBLE);
            mBinding.etPetCaseName.setText(caseInfo.getName());
            mBinding.etRemark.setText(caseInfo.getRemarks());

            try {
                String urlsJson = caseInfo.getPathologyAlbum().replace("\\", "");
                JSONArray jsonArray = new JSONArray(urlsJson);
                for (int i = 0; i < jsonArray.length(); i++) {
                    photoList.add(jsonArray.getString(i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.ivRight.setOnClickListener(v -> {
            DelCaseAlertDialog alertDialog = new DelCaseAlertDialog(this,getString(R.string.dialog_tips));
            alertDialog.setShowRelativeLayoutButton(v1 -> {
                loading();
                petViewModel.deletePathology(caseInfo);
            },v1 -> alertDialog.dismiss());
            alertDialog.show();
        });
        photoAdapter = new PhotoAdapter(this, photoList, this);

        mBinding.rvPhotos.setLayoutManager(new GridLayoutManager(this, 4)); // 网格布局，3列
        mBinding.rvPhotos.addItemDecoration(new GridSpacingItemDecoration(10));
        mBinding.rvPhotos.setAdapter(photoAdapter);
        mBinding.textView1.setText(String.format(getString(R.string.pet_photo_case), photoList.size()));

        mBinding.tvNext.setOnClickListener(v -> {
            ArrayList<String> pathList = new ArrayList<>();
            for (String uri : photoList) {
                if (!uri.toString().startsWith("http")) {
                    pathList.add(uri);
                }
            }
            petCaseName = mBinding.etPetCaseName.getText().toString().trim();
            if (TextUtils.isEmpty(petCaseName)) {
                Toast.makeText(this, "请输入宠物病例名称", Toast.LENGTH_SHORT).show();
                return;
            }
            if (petCaseName.length() > 20) {
                Toast.makeText(this, "病例名称不能超过20个字符", Toast.LENGTH_SHORT).show();
                return;
            }

            String remark = mBinding.etRemark.getText().toString();
            if (remark.length() > 200) {
                Toast.makeText(this, "备注不能超过200个字符", Toast.LENGTH_SHORT).show();
                return;
            }


            handler.sendEmptyMessage(0);
            AsyncMultiFileUploader.uploadFiles(this, pathList, uploadMultifileCallback);
        });
    }

    private UploadMultifileCallback uploadMultifileCallback = new UploadMultifileCallback() {
        @Override
        public void onUploadSuccess(String fileName) {
            uploadUrl.add(fileName);
        }

        @Override
        public void onUploadFailure(String fileName, String error) {
            handler.sendEmptyMessage(2);
        }

        @Override
        public void onAllUploadsComplete(int successCount, int failureCount) {
            if (caseInfo == null) {
                caseInfo = new CaseInfo();
            }
            caseInfo.setPetId(petId);
            caseInfo.setName(petCaseName);
            caseInfo.setRemarks(mBinding.etRemark.getText().toString().trim());

            for (String uri : photoList) {
                if (uri.toString().startsWith("http")) {
                    uploadUrl.add(uri.toString());
                }
            }

            caseInfo.setPathologyAlbum(ListUtils.convertArrayListToFormattedString(uploadUrl));

            if (!isEdit) {
                petViewModel.addPathology(caseInfo);
            } else {
                petViewModel.updatePathology(caseInfo);
            }
        }
    };

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                loading();
            } else if (msg.what == 1) {
                dismiss();
                Toast.makeText(CaseInfoActivity.this, "照片上传失败", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });

    private void showSelectPhotoDialog() {
        DialogUtils.showSelectDialog(this, v -> {
            PictureSelector.create(this)
                    .openGallery(SelectMimeType.ofImage()) // 选择图片
                    .setImageEngine(GlideEngine.createGlideEngine()) // 使用 Glide 加载图片
                    .setMaxSelectNum(10 - photoList.size())
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            // 处理返回的图片
                            for (LocalMedia media : result) {
                                int size = photoList.size() - 1;
                                photoList.add(media.getRealPath());
                                photoAdapter.notifyItemChanged(size, photoList.size() - 1);
                                mBinding.textView1.setText(String.format(getString(R.string.pet_photo_case), photoList.size()));
                            }
                        }
                        @Override
                        public void onCancel() {}
                    });
        }, v -> {
            PictureSelector.create(this)
                    .openCamera(SelectMimeType.ofImage()) // 拍照
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            for (LocalMedia media : result) {
                                int size = photoList.size() - 1;
                                photoList.add(media.getRealPath());
                                photoAdapter.notifyItemChanged(size, photoList.size() - 1);
                                mBinding.textView1.setText(String.format(getString(R.string.pet_photo_case), photoList.size()));
                            }
                        }
                        @Override
                        public void onCancel() {}
                    });
        });
    }

    private void checkAndRequestPermissions() {
        if (!PermissionManager.hasPermissions(this, PermissionManager.REQUIRED_PERMISSIONS)) {
            requestPermissions(PermissionManager.REQUIRED_PERMISSIONS, PERMISSION_REQ_ID);
        } else {
            showSelectPhotoDialog();
        }
    }

    @Override
    public void onPermissionsResultSuccess() {
        super.onPermissionsResultSuccess();
        showSelectPhotoDialog();
    }

    @Override
    public void onAddPhotoClick() {
        // 添加图片逻辑
        if (photoList.size() < 10) {
            checkAndRequestPermissions();
        } else {
            Toast.makeText(this, "最多只能添加10张图片", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDeletePhotoClick(int position) {
        // 删除图片逻辑
        int actualPosition = position - (photoList.size() < 10 ? 1 : 0);
        photoList.remove(actualPosition);
        photoAdapter.notifyDataSetChanged();
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context, int petId) {
        Intent intent = new Intent(context, CaseInfoActivity.class);
        intent.putExtra("petId", petId);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, CaseInfo caseInfo, int petId) {
        Intent intent = new Intent(context, CaseInfoActivity.class);
        intent.putExtra("caseInfo", caseInfo);
        intent.putExtra("petId", petId);
        context.startActivity(intent);
    }
}